package predicates

import (
	"sigs.k8s.io/cluster-api/util/conditions"
	"sigs.k8s.io/controller-runtime/pkg/event"
	"sigs.k8s.io/controller-runtime/pkg/predicate"

	bkev1beta1 "gopkg.openfuyao.cn/cluster-api-provider-bke/api/v1beta1"
)

func BKEMachineConditionUpdate() predicate.Funcs {
	return predicate.Funcs{
		UpdateFunc: func(e event.UpdateEvent) bool {
			if newObj := e.ObjectNew.(*bkev1beta1.BKEMachine); newObj != nil {
				if oldObj := e.ObjectOld.(*bkev1beta1.BKEMachine); oldObj != nil {
					oldCondition := conditions.Get(oldObj, bkev1beta1.BootstrapSucceededCondition)
					newCondition := conditions.Get(newObj, bkev1beta1.BootstrapSucceededCondition)
					if oldCondition == nil && newCondition != nil {
						return true
					}
					if oldCondition == nil || newCondition == nil {
						return false
					}
					oldConditionTime := oldCondition.LastTransitionTime
					newConditionTime := newCondition.LastTransitionTime
					return oldConditionTime != newConditionTime
				}
			}
			return false
		},
		CreateFunc:  func(event.CreateEvent) bool { return false },
		DeleteFunc:  func(event.DeleteEvent) bool { return false },
		GenericFunc: func(event.GenericEvent) bool { return false },
	}
}
